package com.qf.controller;

import com.qf.commons.TableData;
import com.qf.entity.EndUser;
import com.qf.entity.Notify;
import com.qf.service.NotifyService;
import com.qf.timejob.SseEmitterJob;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@CrossOrigin("*")
@RestController
public class NotifyController {
    //本地图片路径
    @Value("${imgLocalPath}")
    private String imgLocalPath;
    //nginx服务器路径
    @Value("${serverImgPath}")
    private String serverImgPath;
    @Value("${serverTextPath}")
    private String serverTextPath;
    @Value("${notifyLocalPath}")
    private String notifyLocalPath;


    @Resource
    private NotifyService notifyService;
    //查看所有通知信息
    @GetMapping("/notify")
    public Object getAllNotify(Integer uid,Integer offset,Integer limit){ //uid=3&order=asc&offset=0&limit=10&_=1593690464818

        Map tableData = notifyService.getTableNotify(uid, offset, limit);
        System.out.println(tableData.toString());
        return tableData;
    }
    //添加通知状态
    @PutMapping("/notify/addReadNotitfy")
    public Map changeNotifyStatus( Integer uid,Integer nid){
        Map<String,Object> resutlMap = new HashMap<>();
        notifyService.changeNotifyStatus(uid,nid);
        return resutlMap;
    }
    @PostMapping("/notify/uploadImg")
    public Map uploadNotifyImg(MultipartFile file) {
        //文件的原始名称
        String filename = file.getOriginalFilename();
        //定制全局唯一的命名
        String unique = UUID.randomUUID().toString();
        //获得文件的后缀
        String ext = FilenameUtils.getExtension(filename);//abc.txt   txt    hello.html  html
        //定制全局唯一的文件名
        String uniqueFileName = unique+"."+ext;
        //文件的类型
        String type = file.getContentType();
        //获得 upload_file的磁盘路径 ==> 在webapp目录下创建一个目录"upload_file",且此目录初始不要为空，否则编译时被忽略
        File imgfile = new File(imgLocalPath+"/"+uniqueFileName);
        //如果父目录不存在则自动创建
        File fileParent = imgfile.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        //将上传的文件，存入磁盘路径中
        //source.transferTo(new File("d:/xxxx/xxxx/xx.jpg"))
        try {
            file.transferTo(imgfile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回在nignx服务器的路径
        String imgPath = serverImgPath+uniqueFileName;
        Map<String,String> map = new HashMap<>();
        map.put("location",imgPath);
        return map;
    }

    @PostMapping("/notify/uploadNotifyFile")
    public Map uploadNotifyFile(String notifyContent){
        System.out.println(notifyContent);
        //定制全局唯一的命名
        String unique = System.currentTimeMillis()+((int)(Math.random()*100)+1)+".html";
        //文件本地路径
        String localPath = notifyLocalPath+"/"+unique;
        try {
            File file = new File(localPath);
            //如果父目录不存在则自动创建
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            PrintStream ps = new PrintStream(new FileOutputStream(file));
            ps.println(notifyContent);// 往文件里写入字符串
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //返回在nignx服务器的路径
        String textPath = serverTextPath+unique;
        Map<String,String> map = new HashMap<>();
        map.put("textPath",textPath);
        return map;
    }
    //插入新的通知
    @PostMapping("/notify/addNotify")
    public Map addNofity(Integer uid, String title, String path){
        notifyService.insertNotify(uid, title, path);
        Map<String,Object> resutlMap = new HashMap<>();

        //刷新定时任务的通知判断
        SseEmitterJob.setHasNewNotify(true);
        return resutlMap;
    }
    //获取所有未读通知
    @GetMapping("/notify/unread")
    public Map getUnreadNotify(Integer uid){
        Map<String,Object> resutlMap = new HashMap<>();
        List<Notify> list = notifyService.getUnreadNotify(uid);
        resutlMap.put("code","1");
        resutlMap.put("notify",list);
        return resutlMap;
    }
    //获取未读通知总数
    @GetMapping("/notify/unread/count")
    public Map getUnreadNotifyCount(Integer uid){
        Integer count = notifyService.getUnreadNotifyCount(uid);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",1);
        resultMap.put("count",count);
        return resultMap;
    }

    //获取已登录用户id
    @GetMapping("/getUid")
    public Map getUserId(HttpSession session){
        Map<String,Object> resultMap = new HashMap<>();
        EndUser user = (EndUser) session.getAttribute("endUser");
        Integer uid = user.getId();
        if(uid==null){
            resultMap.put("code",2);
            resultMap.put("msg","无法获取已登录用户id");
            return resultMap;
        }else {
            resultMap.put("code",1);
            resultMap.put("uid",uid);
            return resultMap;
        }
    }

    //根据路径把静态资源转换成文本内容
    @GetMapping("/getNotify")
    public Map getNotifyContent(String path){
        Map<String ,Object> resultMap  =new HashMap<>();
        String localPath = notifyLocalPath+"/"+path;
        System.out.println(localPath);
        StringBuffer sb = new StringBuffer();
        String lineTxt = null;
        try {
            String encoding="GBK";
            File file=new File(localPath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);

                while((lineTxt = bufferedReader.readLine()) != null){
                    System.out.println(lineTxt);
                    sb.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        resultMap.put("code",1);
        resultMap.put("content",sb.toString());
        return resultMap;
    }

    //修改通知内容
    @GetMapping("/notify/editNotify")
    public Map editNotify(Integer nid,String title,String path,HttpSession session){
        Map resultMap = new HashMap();
        EndUser user = (EndUser) session.getAttribute("endUser");
        Integer uid = user.getId();
        notifyService.changeNotifyContent(uid,title,path,nid);
        //刷新定时任务的通知判断
        SseEmitterJob.setHasNewNotify(true);
        return resultMap;
    }
}
